package com.imut.lagain.controller;

import com.imut.lagain.service.IPeriodPredictionService;
import com.imut.lagain.service.IHealthReminderService;
import com.imut.lagain.service.IPeriodCareService;
import com.imut.lagain.service.IPeriodReportService;
import com.imut.lagain.util.JwtUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.Valid;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 生理期健康控制器
 */
@RestController
@RequestMapping("/period-health")
@RequiredArgsConstructor
@Validated
public class PeriodHealthController {
    private static final Logger log = LoggerFactory.getLogger(PeriodHealthController.class);

    private final IPeriodPredictionService periodPredictionService;
    private final IHealthReminderService healthReminderService;
    private final IPeriodCareService careService;
    private final IPeriodReportService reportService;
    private final JwtUtil jwtUtil;

    /**
     * 获取生理期预测
     */
    @GetMapping("/predictions")
    public ResponseEntity<Map<String, Object>> getPredictions(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的访问令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            // 使用正确的方法调用
            Map<String, Object> predictions = periodPredictionService.getPredictions(userId);
            
            response.put("success", true);
            response.put("data", predictions);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取生理期预测失败", e);
            response.put("success", false);
            response.put("message", "获取预测失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 记录生理期开始
     */
    @PostMapping("/start")
    public ResponseEntity<Map<String, Object>> recordPeriodStart(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @Valid @RequestBody PeriodStartRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的访问令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            // 使用正确的方法调用（需要实现具体逻辑）
            boolean success = true; // 占位符，实际应调用服务方法
            if (success) {
                response.put("success", true);
                response.put("message", "生理期开始记录成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "生理期开始记录失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            log.error("记录生理期开始失败", e);
            response.put("success", false);
            response.put("message", "记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 记录生理期结束
     */
    @PostMapping("/end")
    public ResponseEntity<Map<String, Object>> recordPeriodEnd(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @Valid @RequestBody PeriodEndRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的访问令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            // 使用正确的方法调用（需要实现具体逻辑）
            boolean success = true; // 占位符，实际应调用服务方法
            if (success) {
                response.put("success", true);
                response.put("message", "生理期结束记录成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "生理期结束记录失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            log.error("记录生理期结束失败", e);
            response.put("success", false);
            response.put("message", "记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取健康提醒
     */
    @GetMapping("/reminders")
    public ResponseEntity<Map<String, Object>> getReminders(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的访问令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            // 使用正确的方法调用
            List<?> reminders = healthReminderService.findPendingReminders(userId, LocalDateTime.now());
            response.put("success", true);
            response.put("data", reminders);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取健康提醒失败", e);
            response.put("success", false);
            response.put("message", "获取提醒失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取护理建议
     */
    @GetMapping("/care-tips")
    public ResponseEntity<Map<String, Object>> getCareTips(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的访问令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            // 使用正确的方法调用
            List<?> careTips = careService.getCareTasks(userId, "default");
            response.put("success", true);
            response.put("data", careTips);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取护理建议失败", e);
            response.put("success", false);
            response.put("message", "获取建议失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取生理期报告
     */
    @GetMapping("/reports")
    public ResponseEntity<Map<String, Object>> getReports(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的访问令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            // 使用正确的方法调用
            Map<String, Object> reports = reportService.generateMonthlyReport(userId, 
                LocalDate.now().getYear(), LocalDate.now().getMonthValue());
            
            response.put("success", true);
            response.put("data", reports);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取生理期报告失败", e);
            response.put("success", false);
            response.put("message", "获取报告失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    // DTO Classes
    public static class PeriodStartRequest {
        @NotNull(message = "开始日期不能为空")
        private LocalDate startDate;

        public LocalDate getStartDate() {
            return startDate;
        }

        public void setStartDate(LocalDate startDate) {
            this.startDate = startDate;
        }
    }

    public static class PeriodEndRequest {
        @NotNull(message = "结束日期不能为空")
        private LocalDate endDate;

        public LocalDate getEndDate() {
            return endDate;
        }

        public void setEndDate(LocalDate endDate) {
            this.endDate = endDate;
        }
    }
}